package org.lq.shopping.util;

import javax.sql.DataSource;
import com.alibaba.druid.pool.DruidDataSource;

public class DruidUtil {

	/**
	 * 创建德鲁伊数据库连接池
	 * 数据库连接生成类,返回一个数据库连接对象
	 * 构造函数完成数据库驱动的加载和数据库的连接
	 */
	private static DruidDataSource dataSource = null;
	private static String URL = ProperUtil.getValueByKey("jdbc.url");
	private static String DRIVER = ProperUtil.getValueByKey("jdbc.driver");
	private static String NAME = ProperUtil.getValueByKey("jdbc.name");
	private static String PWD = ProperUtil.getValueByKey("jdbc.pwd");
	
	public static DataSource getDataSource(){
		try {
			if(dataSource == null) {
				dataSource = new DruidDataSource();
				//设置连接参数
				dataSource.setUrl(URL);
				dataSource.setDriverClassName(DRIVER);
				dataSource.setUsername(NAME);
				dataSource.setPassword(PWD);
				//配置初始化大小,最小值,最大值
				dataSource.setInitialSize(1);//初始化时建立物理连接的个数
				dataSource.setMinIdle(1);
				dataSource.setMaxActive(20);
				//连接泄露检测,德鲁伊特有
				dataSource.setRemoveAbandoned(true);
				dataSource.setRemoveAbandonedTimeout(30);
				//配置获取连接等待超时的时间
				dataSource.setMaxWait(20000);
				//配置 间隔多久才进行一次检测,检测需要关闭的空闲连接
				dataSource.setTimeBetweenEvictionRunsMillis(20000);
				//防止过期
				dataSource.setValidationQuery("select 1 from dual");
				dataSource.setTestWhileIdle(true);
				dataSource.setTestOnBorrow(true);
			}
		} catch (Exception e) {
			throw e;
		}
		return dataSource;
	}
}
